﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Net;
using System.Runtime.InteropServices;

namespace monitor
{
    class Monitor
    {
        //程序入口
        static void Main(String[] args)
        {
            //配置文件，读取配置文件，获取上报url和是否开启日志。
            string ip_url = "", log_open = "";
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.ini");
            if(File.Exists(path))
            {
                ip_url = INIHelper.Read("ip", "url", "", path);
                log_open = INIHelper.Read("log", "open", "", path);
            }
            //没有配置url
            if (ip_url == null || ip_url == "") { return; }

            //分别执行命令，接受结果，并将结果发送到服务器
            //ip ipconfig | find /i "IPv4 地址" 
            String ip = ExecuteCmd.GetIp();
            //os_name 操作系统 systeminfo | find /i "OS 名称"
            String os_name = ExecuteCmd.GetOsName();
            //os_arch 系统架构 systeminfo | find /i "系统类型"
            String os_arch = ExecuteCmd.GetOsArch();
            //host_name 主机名 systeminfo | find /i "主机名"
            String host_name = ExecuteCmd.GetHostName();
            //physical_processor 物理核心 wmic cpu get NumberOfCores
            String physical_processor = ExecuteCmd.GetPhysicalProcessor();


            //cpu_free 获取cpu 空闲 wmic cpu get loadpercentage
            String cpu_free = ExecuteCmd.GetCpuFree();
            //mem_total 总内存 systeminfo | find /i "物理内存总量"
            String mem_total = ExecuteCmd.GetMemTotal();
            //mem_free 可用内存 systeminfo | find /i "可用的物理内存"
            String mem_free = ExecuteCmd.GetMemFree();
            //disk_data 全部磁盘信息 Wmic logicaldisk
            String disk_data = ExecuteCmd.GetDiskData();
            //process_data 全部进程信息 wmic process list brief
            String process_data = ExecuteCmd.GetDiskProcess();

            String data = "";//拼接发送到服务器的json字符串
            if(ip != null && ip != ""){ data += "\"ip\":\"" + ip + "\""; }
            if (os_name != null && os_name != ""){if (data != null && data != "") { data += ","; } data += "\"os_name\":\"" + os_name + "\""; }
            if (os_arch != null && os_arch != "") { if (os_name != null && data != "") { data += ","; } data += "\"os_arch\":\"" + os_arch + "\""; }
            if (host_name != null && host_name != "") { if (data != null && data != "") { data += ","; } data += "\"host_name\":\"" + host_name + "\""; }
            if (physical_processor != null && physical_processor != "") { if (data != null && data != "") { data += ","; } data += "\"physical_processor\":\"" + physical_processor + "\""; }
            if (cpu_free != null && cpu_free != "") { if (data != null && data != "") { data += ","; } data += "\"cpu_free\":\"" + cpu_free + "\""; }
            if (mem_total != null && mem_total != "") { if (data != null && data != "") { data += ","; } data += "\"mem_total\":\"" + mem_total + "\""; }
            if (mem_free != null && mem_free != "") { if (data != null && data != "") { data += ","; } data += "\"mem_free\":\"" + mem_free + "\""; }
            if (disk_data != null && disk_data != "") { if (data != null && data != "") { data += ","; } data += "\"disk_data\":\"" + disk_data + "\""; }
            if (process_data != null && process_data != "") { if (data != null && data != "") { data += ","; } data += "\"process_data\":\"" + process_data + "\""; }


            //如果没有数据不必向下执行
            if (data == null || data == "") { return; }
            data = "{" + data + "}";
            //写入日志
            //WriteLog(data);
            //将数据发送到服务器
            String response = Post(ip_url, data);
            //写入日志
            if(log_open== "true")
            {
                String log = "data: ( " + data + " ); response: (" + response + ");";
                WriteLog(log);
            }
        }

        //数据发送到服务器
        public static String Post(String url, String data)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            byte[] byteData = Encoding.UTF8.GetBytes(data);
            int length = byteData.Length;
            request.ContentLength = length;
            Stream writer = request.GetRequestStream();
            writer.Write(byteData, 0, length);
            writer.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            return new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
        }

        //生成本地日志实现
        public static void WriteLog(string log)
        {
            //日志文件放在当前文件夹下，每天一个日志文件
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyy-MM-dd") + ".log");
            FileStream fileStream;
            StreamWriter streamWriter;
            //验证文件是否存在，有则追加，无则创建
            if (File.Exists(path))
            {
                fileStream = new FileStream(path, FileMode.Append, FileAccess.Write);
            }
            else
            {
                fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
            }
            streamWriter = new StreamWriter(fileStream);
            streamWriter.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")+":" + log);
            streamWriter.Close();
            fileStream.Close();
        }
    }
}
